package com.loopy.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;

public class hspFilterConfig implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String filterName = filterConfig.getFilterName();
        System.out.println("filterName="+filterName);
        String ip = filterConfig.getInitParameter("ip");
        System.out.println("ip="+ip);
        ServletContext servletContext = filterConfig.getServletContext();
        servletContext.setAttribute("ip",ip);
        Enumeration<String> initParameterNames = filterConfig.getInitParameterNames();
        while (initParameterNames.hasMoreElements()){
            System.out.println("名字"+initParameterNames.nextElement());
        }

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("doFilter被调用");
        String ip = (String)servletRequest.getServletContext().getAttribute("ip");
        String remoteAddr = ((HttpServletRequest) servletRequest).getRemoteAddr();
        if(remoteAddr.contains(ip)){
            servletRequest.getRequestDispatcher("/login.jsp").forward(servletRequest, servletResponse);
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
